package com.xtaller.lazy.lib.kit;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import com.xtaller.lazy.lib.bean.JWTResult;
import com.xtaller.lazy.lib.convert.J;
import io.jsonwebtoken.*;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
import java.util.HashMap;

/**
 * @version V1.0
 * @author: Taller
 * @date: 2019-04-03
 * @Description: jwt工具类
 */
public class JwtUtil {
    public static final int JWT_ERRCODE_EXPIRE = 4001;			//Token过期
    public static final int JWT_ERRCODE_FAIL = 4002;			//验证不通过
    public static final String JWT_SECRET = "8677df7fc2018030361c114d5ec8245d";			//密匙


    /**
     * 签发JWT
     * @param id
     * @param info   认证数据
     * @param ttlMillis
     * @return  String
     */
    public static String createJWT(Long id, HashMap<String, Object> info, long ttlMillis) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        SecretKey secretKey = generalKey();
        JwtBuilder builder = Jwts.builder()
                .setId(id + "")
                .setSubject(J.o2s(info))                        // 主题
                .setIssuer("lazy-taller")                       // 签发者
                .setIssuedAt(now)                               // 签发时间
                .signWith(signatureAlgorithm, secretKey);       // 签名算法以及密匙
        if (ttlMillis > 0) {
            long expMillis = nowMillis + ttlMillis;
            Date expDate = new Date(expMillis);
            builder.setExpiration(expDate); // 过期时间
        }
        return builder.compact();
    }


    /**
     * 验证JWT
     * @param jwtStr
     * @return
     */
    public static JWTResult validateJWT(String jwtStr) {
        JWTResult jwt = new JWTResult();
        Claims claims = null;
        try {
            claims = parseJWT(jwtStr);
            jwt.setSuccess(true);
            jwt.setClaims(claims);
            jwt.setUserId(Long.parseLong(claims.getId()));
        } catch (ExpiredJwtException e) {
            jwt.setErrCode(JWT_ERRCODE_EXPIRE);
            jwt.setSuccess(false);
        } catch (SignatureException e) {
            jwt.setErrCode(JWT_ERRCODE_FAIL);
            jwt.setSuccess(false);
        } catch (Exception e) {
            jwt.setErrCode(JWT_ERRCODE_FAIL);
            jwt.setSuccess(false);
        }
        return jwt;
    }

    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.decode(JWT_SECRET);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     *
     * 解析JWT字符串
     * @param jwt
     * @return
     * @throws Exception
     */
    private static Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }
}
